package com.pethospital.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pethospital.common.Result;
import com.pethospital.dto.PetDTO;
import com.pethospital.entity.Pet;
import com.pethospital.service.PetService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/pet")
public class PetController {

    @Resource
    private PetService petService;
    
    @Resource
    private com.pethospital.util.FileUploadUtil fileUploadUtil;
    
    /**
     * 安全地将userId对象转换为Long类型
     */
    private Long safeConvertToLong(Object userIdObj) {
        if (userIdObj instanceof Integer) {
            return ((Integer) userIdObj).longValue(); // 将Integer转换为Long
        } else if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        } else {
            return Long.valueOf(userIdObj.toString()); // 尝试将其他类型转换为Long
        }
    }

    /**
     * 添加宠物
     */
    @PostMapping
    public Result<Long> add(@RequestBody @Valid PetDTO petDTO, HttpServletRequest request) {
        Long userId = safeConvertToLong(request.getAttribute("userId"));
        Long petId = petService.add(petDTO, userId);
        return Result.success(petId);
    }

    /**
     * 更新宠物信息
     */
    @PutMapping
    public Result<Void> update(@RequestBody @Valid PetDTO petDTO, HttpServletRequest request) {
        Long userId = safeConvertToLong(request.getAttribute("userId"));
        petService.update(petDTO, userId);
        return Result.success();
    }

    /**
     * 删除宠物
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id, HttpServletRequest request) {
        Long userId = safeConvertToLong(request.getAttribute("userId"));
        petService.delete(id, userId);
        return Result.success();
    }

    /**
     * 获取宠物详情
     */
    @GetMapping("/{id}")
    public Result<Pet> getById(@PathVariable Long id) {
        Pet pet = petService.getById(id);
        return Result.success(pet);
    }

    /**
     * 分页获取用户的宠物列表
     */
    @GetMapping("/list")
    public Result<Page<Pet>> list(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int size,
                                  HttpServletRequest request) {
        Long userId = safeConvertToLong(request.getAttribute("userId"));
        Page<Pet> petPage = petService.pageByUserId(userId, page, size);
        return Result.success(petPage);
    }

    /**
     * 上传宠物照片
     */
    @PostMapping("/photo")
    public Result<String> uploadPhoto(@RequestParam("file") MultipartFile file) {
        String photoUrl = fileUploadUtil.uploadFile(file, "pet");
        return Result.success(photoUrl);
    }
} 